package com.senthink.gl.business.fault;

import com.senthink.gl.business.common.exception.BusinessException;
import com.senthink.gl.business.device.people.SwitchEnum;
import com.senthink.gl.business.messages.CodeMsg;
import lombok.Getter;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 故障类型枚举定义
 *
 * @author zooqi@senthink.com
 * @data 2017/12/04
 */
@Getter
public enum FaultTypeEnum {

    ON(1, "开"),

    OFF(2, "关"),

    NORMAL(3, "正常"),

    ONLINE(4, "在线"),

    OFFLINE(5, "离线"),

    POWER_ABNORMAL(6, "功率异常"),

    MAINTENANCE(7, "维修中");

    private Integer faultType;

    private String faultName;

    private static final Map<Integer, FaultTypeEnum> pool = new ConcurrentHashMap<>();

    private static final List<Integer> faultList = new LinkedList<>();

    static {
        for (FaultTypeEnum enums : FaultTypeEnum.values()) {
            pool.put(enums.getFaultType(), enums);
        }

        faultList.add(OFFLINE.getFaultType());
        faultList.add(POWER_ABNORMAL.getFaultType());
        faultList.add(MAINTENANCE.getFaultType());
    }

    FaultTypeEnum(Integer faultType, String faultName) {
        this.faultType = faultType;
        this.faultName = faultName;
    }

    public static FaultTypeEnum fromType(Integer faultType, CodeMsg codeMsg) {
        if (faultType == null) {
            throw new BusinessException(codeMsg.illegalArgumentCode(), codeMsg.illegalArgumentMsg());
        }
        return Optional.ofNullable(pool.get(faultType))
                .orElseThrow(() -> new BusinessException(codeMsg.illegalArgumentCode(), codeMsg.illegalArgumentMsg()));
    }

    public static FaultTypeEnum fromType(Integer faultType) {
        if (faultType == null) {
            throw new IllegalArgumentException();
        }
        return Optional.ofNullable(pool.get(faultType))
                .orElseThrow(IllegalArgumentException::new);
    }

    public static FaultTypeEnum fromSwitch(SwitchEnum switchEnum) {
        if (switchEnum == SwitchEnum.ON) {
            return FaultTypeEnum.ON;
        }
        return FaultTypeEnum.OFF;
    }

    /**
     * 判断设备是否故障
     *
     * @param faultType
     * @return
     */
    public static boolean isFault(Integer faultType) {
        return POWER_ABNORMAL.getFaultType().equals(faultType) || MAINTENANCE.getFaultType().equals(faultType);
    }

    /**
     * 获取故障状态列表
     *
     * @return
     */
    public static List<Integer> getFaultList() {
        return faultList;
    }
}
